//
//  gerAddressController.m
//  1243
//
//  Created by 杨森 on 16/5/17.
//  Copyright © 2016年 1243. All rights reserved.
//

#import "gerAddressController.h"
#import "getAddressCell.h"
#import "NetWorkTools.h"
#import "AddAddressViewController.h"

@interface gerAddressController ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>

@property(nonatomic,strong)UITableView *addressTableView;

@property (nonatomic,strong) NSMutableArray *GetAddressArray;

@property(nonatomic,assign)BOOL chooseStaus;

@property (nonatomic, strong) NSMutableArray *cellArr;

@property(nonatomic,strong)NSDictionary *deleteDict;

@property(nonatomic,assign,getter=isDeleteDefault)BOOL deleteDefault;

@end

@implementation gerAddressController

- (NSMutableArray *)GetAddressArray {
    if (!_GetAddressArray) {
        _GetAddressArray = [NSMutableArray array];
    }
    return _GetAddressArray;
}

- (NSMutableArray *)cellArr {
    if (!_cellArr) {
        _cellArr = [NSMutableArray array];
    }
    return _cellArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    
    self.title = @"地址管理";
    [self addTableViewUI];
    self.deleteDefault = NO;

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self loadUserAddressData];
}


- (void)addTableViewUI
{
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    UITableView *addressTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WEITH, HEIGHT-64-40) style:UITableViewStyleGrouped];
    [self.view addSubview:addressTableView];
    self.addressTableView = addressTableView;
    
    addressTableView.delegate = self;
    addressTableView.dataSource = self;
    
    addressTableView.rowHeight = 110;
    
    //添加新地址
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:btn];
    btn.frame = CGRectMake(0,HEIGHT-40-64, WIDTH, 40);
    [btn setBackgroundColor:[UIColor orangeColor]];
    btn.titleLabel.font = [UIFont systemFontOfSize:14];
    [btn setTitle:@"+ 添加新地址" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(didCreatBarButton) forControlEvents:UIControlEventTouchUpInside];
    
}

- (void)didCreatBarButton
{
    AddAddressViewController *addAddressVC = [[AddAddressViewController alloc] init];
    addAddressVC.num = 0;
    addAddressVC.arrM = [NSMutableArray array];
    [addAddressVC.arrM addObjectsFromArray:self.GetAddressArray];
    
    [self.navigationController pushViewController:addAddressVC animated:YES];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.GetAddressArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identifier = @"getAddressCell";
    
    getAddressCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (cell==nil) {
        cell= [[[NSBundle mainBundle] loadNibNamed:@"getAddressCell" owner:nil options:nil] lastObject];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        /*
         
         AddTime = "<null>";
         Address = "\U6d4b\U8bd5454";
         City = "\U5ef6\U8fb9\U671d\U9c9c\U65cf\U81ea\U6cbb\U5dde";
         ContactMobile = 15434;
         ContactName = test2324;
         ContactPhone = 15434;
         ContactPostCode = 155636845454;
         Countory = "\U6566\U5316\U5e02";
         Id = 47;
         IsDefault = 0;
         Province = "\U5409\U6797\U7701";
         UserId = 1002;
         */

    }
    
    NSDictionary *dict = self.GetAddressArray[indexPath.section];
    NSLog(@"%@", dict[@"IsDefault"]);
    //姓名
    cell.nameLabel.text = [NSString stringWithFormat:@"%@",dict[@"ContactName"]];
    //电话
    cell.phoneLabel.text = [NSString stringWithFormat:@"%@",dict[@"ContactPhone"]];
    //地址
    cell.addressLabel.text = [NSString stringWithFormat:@"%@",dict[@"Address"]];
    
    [cell.defaultBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected];
    [cell.defaultBtn setImage:[UIImage imageNamed:@"icon_mr_h"] forState:UIControlStateSelected];
    [cell.defaultBtn setTitle:@"默认地址" forState:UIControlStateSelected];
    
    [cell.defaultBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [cell.defaultBtn setImage:[UIImage imageNamed:@"icon_mr_n"] forState:UIControlStateNormal];
    //默认
    if ([dict[@"IsDefault"] isEqual:@(1)]) {
        cell.defaultBtn.selected = YES;

    }else{
        cell.defaultBtn.selected = NO;
  
    }
    
    [cell.defaultBtn setTitle:@"设为默认" forState:UIControlStateNormal];
    [cell.defaultBtn addTarget:self action:@selector(defaultBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    //编辑
    
    [cell.editBtn addTarget:self action:@selector(editBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    //删除
    [cell.deleteBtn addTarget:self action:@selector(deleteBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    return cell;
}

#pragma mark>>>>>>>>> 代理

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.pageIndex == 0) {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"gankuaifagongzi" object:nil userInfo:@{@"CardInfo":self.GetAddressArray[indexPath.section]}];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}




//默认按钮
- (void)defaultBtnClick:(UIButton *)button
{
    getAddressCell * cell = (getAddressCell *)[[button superview] superview];
    NSIndexPath *path = [self.addressTableView indexPathForCell:cell];

    NSLog(@"%ld", path.section);
    if ([self.GetAddressArray[path.section][@"IsDefault"] intValue] == 0) {
        for (int i = 0; i < self.GetAddressArray.count; i ++) {
            int IsDefault = [self.GetAddressArray[i][@"IsDefault"] intValue];
            if (IsDefault == 1) {
                if (path.section == i) {
                    return;
                }
                
                [self.GetAddressArray[path.section] setValue:@(1) forKey:@"IsDefault"];
                [self updateAddressData:self.GetAddressArray[path.section]];
                [self.GetAddressArray[i] setValue:@(0) forKey:@"IsDefault"];
                [self updateAddressData:self.GetAddressArray[i]];
                [self.addressTableView reloadData];
                return;
            }
        }
    }
    
}


//编辑
- (void)editBtnClick:(UIButton *)btn
{
    getAddressCell * cell = (getAddressCell *)[[btn superview] superview];
    NSIndexPath *path = [self.addressTableView indexPathForCell:cell];
    AddAddressViewController *addAddressVC = [[AddAddressViewController alloc] init];
    addAddressVC.num = 1;
    addAddressVC.dic = self.GetAddressArray[path.section];
    [self.navigationController pushViewController:addAddressVC animated:YES];

}

//删除
- (void)deleteBtnClick:(UIButton *)button
{
    getAddressCell * cell = (getAddressCell *)[[button superview] superview];
    NSIndexPath *path = [self.addressTableView indexPathForCell:cell];
    self.deleteDict = self.GetAddressArray[path.section];
    if ([self.deleteDict[@"IsDefault"] isEqual:@(1)]) {
        self.deleteDefault = YES;
    } else {
        self.deleteDefault = NO;
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"确定要删除该地址吗?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag = 10000;
    [alert show];

}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1 && alertView.tag == 10000) {
        
        [self deleteAddressData:self.deleteDict];
        
    }
}

#pragma mark >>>>>>> 删除地址
- (void)deleteAddressData:(NSDictionary *)dict
{
    NSDictionary *userData = [ReadLoginData readLoginData];
    
    NSString *userId = [userData objectForKey:@"Number"];
    
    NSDictionary *params = @{
                             //                             @"UserId":@"1"
                             @"UserId":userId,
                             @"AddressId":dict[@"Id"]
                             };
    
    [[NetWorkTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"DELETEADDRESS" completeBlock:^(id object) {
        NSLog(@"%@",object);
    
        
        if ([object[@"Id"] isEqual:@(0)]) {
            [self loadUserAddressData];
        }
        
    }];
}


#pragma mark >>>>>>> 更新地址
- (void)updateAddressData:(NSDictionary *)dic
{
    [[NetWorkTools sharedNetWorkTools] objectWithURLDict:dic AndMenthodName:@"UPDATEEXPRESS" completeBlock:^(id object) {
        
    }];
}


#pragma mark>>>>> 获取地址
- (void)loadUserAddressData {
    
    [self.GetAddressArray removeAllObjects];
    NSDictionary *userData = [ReadLoginData readLoginData];
    
    NSString *userId = [userData objectForKey:@"Number"];
    
    NSDictionary *params = @{
                             
                             @"UserId":userId
                             };
    
    [[NetWorkTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"EXPRESSQUERY" completeBlock:^(id object) {
        //        NSLog(@"%@",object);
        
        NSLog(@"%@",[object objectForKey:@"BackData"]);
        
        NSString *string = [object objectForKey:@"BackData"];
        NSArray *arr = [NetWorkTools arrayWithJsonString:string];
      
        [self.GetAddressArray  addObjectsFromArray:arr];
        if (self.GetAddressArray.count != 0) {
            if (self.isDeleteDefault) {
                [self.GetAddressArray[0] setValue:@(1) forKey:@"IsDefault"];
                [self updateAddressData:self.GetAddressArray[0]];
                self.deleteDefault = NO;
            }
        }
        
        [self.addressTableView reloadData];
        
    }];
}




@end
